import 'dart:async';

import 'package:architecture/os_size.dart';
import 'package:architecture/shared_preference.dart';
// import 'package:cherrilog/cherrilog.dart';
import 'package:code_preview/code_preview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
// import 'package:simple_native_image_compress/simple_native_image_compress.dart';
import 'package:study_demo/base/theme_controller.dart';
import 'package:study_demo/db/isar.dart';
import 'package:study_demo/ui/tool/distribute_board/distribute_board_page.dart';
// import 'package:window_manager/window_manager.dart';
import 'base/base_chess_controller.dart';
import 'src/rust/frb_generated.dart';
import 'ui/main/main_page.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:architecture/ext_string.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  // await initIsar();
  // await NativeImageCompress.init();
  // await RustLib.init();
  // if (isWindows()) {
  //   await windowManager.ensureInitialized();
  //   // Use it only after calling `hiddenWindowAtLaunch`
  //   windowManager.waitUntilReadyToShow().then((_) async {
  //     // Hide window title bar
  //     await windowManager.setTitle('聚宝盆');
  //     // await windowManager.setAspectRatio(1920.0 / 1200.0);
  //     // await windowManager.setSize(const Size(1920 * 0.7, 1200 * 0.7));
  //     await windowManager.setTitleBarStyle(TitleBarStyle.normal);
  //     windowManager.setResizable(false);
  //     await windowManager.center();
  //     await windowManager.show();
  //     await windowManager.focus();
  //   });
  // }
  CodePreview.config = CodePreviewConfig(codeTheme: CodeTheme.light);

  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);

  _runApp();
}

initLogger() async {
  // var logger = await CherriLog.init(
  //   options: CherriOptions()
  //     ..logLevelRange = CherriLogLevelRanges.all
  //     ..useBuffer = false,
  // );
  // logger.logTo(CherriConsole());
}

Future<void> _runApp() async {
  var sharedPreferences = await initSharedPreferences();
  Get.put(sharedPreferences);

  initLogger();

  initFlagPainters();

  runApp(EasyLocalization(
      useOnlyLangCode: true,
      supportedLocales: const [
        Locale('zh'),
        // Locale('en'),
      ],
      path: 'assets/translations',
      fallbackLocale: const Locale('zh'),
      saveLocale: false,
      child: _home()));
}

class _home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    {
      return GetX<ThemeController>(
          init: ThemeController(),
          builder: (controller) {
            return GetMaterialApp(
                title: 'app_name'.translate(),
                localizationsDelegates: context.localizationDelegates,
                supportedLocales: context.supportedLocales,
                locale: context.locale,
                // transitionDuration: Duration(milliseconds: 500),
                debugShowCheckedModeBanner: false,
                defaultTransition: Transition.topLevel,
                theme: ThemeData(
                  brightness:
                      isDarkMode.value ? Brightness.dark : Brightness.light,
                  fontFamily: 'SiYuan',
                  primarySwatch: Colors.blue,
                  appBarTheme: AppBarTheme(
                      color: Colors.deepPurpleAccent,
                      iconTheme: IconThemeData(color: Colors.white),
                      titleTextStyle:
                          TextStyle(color: Colors.white, fontSize: 17)),
                ),
                builder: (context, child) => Scaffold(
                      // Global GestureDetector that will dismiss the keyboard
                      body: GestureDetector(
                        onTap: () {
                          hideKeyboard(context);
                        },
                        child: child,
                      ),
                    ),
                home: MainPage());
            // home: DistributeBoardPage());
          });
    }
  }
}

hideKeyboard(BuildContext context) {
  FocusScopeNode currentFocus = FocusScope.of(context);
  if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
    FocusManager.instance.primaryFocus!.unfocus();
  }
}
